package com.nicolascarrascob.clientesoap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.JsonObject;


public class AddSalaActivity extends Activity {

	private String URL = Constantes.HOST + "/ServicioWebSoap/services/CarteleraCineORMWS";
	private String NAMESPACE = "http://ws.serviciosoap.pds.nicolascarrascob.com";

	
	ArrayList<String> peliculas;
	
	Spinner peliculasSpinner;
	EditText nombreEditText;
	EditText butacasEditText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addsala);
		peliculasSpinner = (Spinner) findViewById(R.id.agregarpelicula_nombre);
	
		nombreEditText = (EditText) findViewById(R.id.addsala_nombre_agregar);
		butacasEditText = (EditText) findViewById(R.id.addsala_butaca_agregar);
	//	estrenoCheckbox = (CheckBox) findViewById(R.id.addpelicula_estreno);
	//	generos = new ArrayList<String>();
		peliculas = new ArrayList<String>();
		new ObtenerGenerosClasificacionBackground().execute();
	}

	public void ingresar(View v){
		JsonObject jsonObjectSala = new JsonObject();
		jsonObjectSala.addProperty("nombre", nombreEditText.getText().toString());
		jsonObjectSala.addProperty("butacas", butacasEditText.getText().toString());
		
		jsonObjectSala.addProperty("pelicula_id", peliculas.get(peliculasSpinner.getSelectedItemPosition()));
//		jsonObjectSala.addProperty("clasificacion_id", clasificaciones.get(clasificacionesSpinner.getSelectedItemPosition()));
		new AddSalaBackground().execute(jsonObjectSala.toString());
	}

	class ObtenerGenerosClasificacionBackground extends AsyncTask<Void, Void, HashMap<String, String>>{
		
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				AddSalaActivity.this,
    				"Cartelera de Cine", 
    				"Espere mientras se carga la cartelera...", 
    				true);
			super.onPreExecute();
		}
		
		@Override
		protected HashMap<String, String> doInBackground(Void... params) {

			HashMap<String, String> resultado = new HashMap<String, String>();
			String peliculasJSON="";
			String METHOD_NAME = "getCartelera";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				peliculasJSON = resultString.toString();
				resultado.put("peliculas", peliculasJSON);

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			

			return resultado;
		}

		@Override
		protected void onPostExecute(HashMap<String, String> result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			//Valido que tenga la informacion necesaria
			if(result.containsKey("peliculas") && !"".equals(result.get("peliculas"))){
				try {
					ArrayList<String> peliculasList = new ArrayList<String>();
					JSONObject generoResultado = new JSONObject(result.get("peliculas"));
					String contenido = generoResultado.getString("Contenido");
					JSONObject peliculasJSONArray = new JSONObject(contenido);
					peliculasJSONArray.names();
					peliculasJSONArray.keys();
					for (Iterator iterator = peliculasJSONArray.keys(); iterator.hasNext();) {
						String string = (String) iterator.next();
						peliculas.add(string);
						peliculasList.add(peliculasJSONArray.getString(string));
						
					}
					
					ArrayAdapter<String> generosAdapter = new ArrayAdapter<String>(AddSalaActivity.this, android.R.layout.simple_spinner_item, peliculasList);
					peliculasSpinner.setAdapter(generosAdapter);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


			}else{
				Toast.makeText(AddSalaActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
			
			
	}
	}
	class AddSalaBackground extends AsyncTask<String, Void, String>{
		
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				AddSalaActivity.this,
    				"Cartelera de Cine", 
    				"Espere mientras se agrega la pelicula...", 
    				true);
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... params) {

			String resultado = new String();
			String METHOD_NAME = "addSala";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("jsonSala", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			//Valido que tenga la informacion necesaria
			if("1".equals(result)){
				Toast.makeText(AddSalaActivity.this, "Ingresada correctamente", Toast.LENGTH_LONG).show();
				finish();
			}else{
				Toast.makeText(AddSalaActivity.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
		}
	}

	}

	
	